from flask import Flask, render_template, request, escape
from log_sys import log_request
import bicycling_direction

key = "ae0c311c2c3f4d41b0888860a62888e9"
app = Flask(__name__)


@app.route('/')
def base():
    title = '骑行路径规划'
    return render_template('entry.html',
                           the_title=title,)


@app.route('/search0', methods=['POST'])
def do_search_0() -> 'html':
    start_address = request.form['start_address']
    end_address = request.form['end_address']
    title = '查询结果'
    df = bicycling_direction.direction_bicycle(key, start_address, end_address)
    results = df.loc[:, ['instruction', 'distance', 'duration']]
    results.columns = ['路线规划', '路程', '时间']
    total_bicycle = bicycling_direction.total_bicycle(df)
    total_bicycle_time = bicycling_direction.total_bicycle_time(df)
    route = results['路线规划'].tolist()
    log_request(request, route)
    return render_template('results.html',
                           the_title=title,
                           the_start_address=start_address,
                           the_end_address=end_address,
                           the_results=results,
                           the_html_table=results.to_html(index=False),
                           the_total_bicycle=total_bicycle,
                           the_total_bicycle_time=total_bicycle_time,)

#用户日志系统页面
@app.route('/viewlog')
def view_the_log() -> 'html':
    contents = []
    with open('bicycling.log', 'r') as log:
        for line in log:
            contents.append([])
            for item in line.split('|'):
                contents[-1].append(escape(item))
    titles = ('用户输入数据', '远程地址', '用户代理', '查询结果')
    return render_template('log.html',
                           the_title='查看日志',
                           the_row_titles=titles,
                           the_data=contents,)

if __name__ == '__main__':
    app.run(debug=True)
